<template>
  <div class="page">
    <!-- 图片区域 -->
    <div class="preview">
      <img :src="imageUrl" alt="" class="preview-image" />
    </div>

    <div class="bottom">
      <!-- 列表区域 -->
      <div class="tpls">
        <div
          v-for="item in templateItems"
          :key="item.template_id"
          class="item"
          :class="{ active: item.template_id === formData.template_id }"
          @click.stop="selectItem(item.template_id)">
          <!-- 第一行：图片 -->
          <div class="image-container">
            <img :src="item.img" :alt="item.name" class="item-image" />
          </div>
          <!-- 第二行：name -->
          <div class="name">
            {{ item.title }}
          </div>
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="bottom-buttons">
        <UpLoadImg @upLoadImg="handleReUpload">
          <button class="btn btn-secondary">Re-upload</button>
        </UpLoadImg>

        <button class="btn btn-primary" @click="handleSubmit">Generate</button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import UpLoadImg from '@/views/activity/components/UpLoadImg.vue';
  import { QShopAPI, QShopType } from '@/api/qshop';
  import router from '@/router/route';
  import { computed, onMounted, ref } from 'vue';
  import { showToast } from 'vant';
  import { useLoginModal } from '@/composables/useLoginModal';
  import { useUserStore } from '@/store/user';

  // 表单数据模型
  const formData = ref({
    type: QShopType.EDIT,
    template_id: 0,
    prompt: '',
  });

  // 提交状态和任务状态
  const isSubmitting = ref(false);

  // 图片URL
  const cropUrl = decodeURIComponent((router.currentRoute.value.query.cropUrl as string) || '');

  const imageUrl = ref(cropUrl);
  const templateItems = ref<any>([]);

  const handleReUpload = () => {
    router.push('/activity/cropImage');
  };

  // 返回
  const goBack = () => {
    router.back();
  };

  // 选择项
  const selectItem = (id: number) => {
    formData.value.template_id = id;
  };

  // 加载分类数据
  const loadCategories = async () => {
    const response = await QShopAPI.getFilterCategorys({});
    templateItems.value = response.data.map((item: any) => ({
      ...item,
      template_id: item.id,
    }));
    formData.value.template_id = templateItems.value[0].template_id;
  };

  // 处理表单提交
  const handleSubmit = async () => {
    if (isSubmitting.value) return;

    try {
      isSubmitting.value = true;

      const prompt_text =
        templateItems.value.find((item: any) => item.template_id === formData.value.template_id)
          ?.prompt_text || '';
      const params = {
        gen_type: formData.value.type,
        template_id: formData.value.template_id,
        prompt_text: prompt_text,
        img: imageUrl.value,
      };

      const res = await QShopAPI.generate(params);
      router.push({
        name: 'ActivityPhotoframeView',
        query: {
          task_id: res.data.task_id || '',
          template_id: formData.value.template_id || '',
          cropUrl: encodeURIComponent(cropUrl),
        },
      });
      // onLoginDialogOpen();
    } catch (error: any) {
      const { code } = error.response.data || {};
      if (code === 100201) {
        showToast('One task at a time, please wait until the current task is finished');
      }
    } finally {
      setTimeout(() => {
        isSubmitting.value = false;
      }, 1000);
    }
  };

  onMounted(() => {
    loadCategories();
  });
</script>

<style scoped lang="scss">
  // 基础样式
  .page {
    height: 100vh;
    height: 100dvh;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    padding-top: 56px;
    padding-bottom: env(safe-area-inset-bottom, 0);
  }
  .head {
    padding: 8px 16px 0 16px;
  }
  .preview {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    // padding: 0 16px;
    img {
      width: 100%;
    }
  }

  .bottom {
    // position: fixed;
    // bottom: 0px;
    // left: 0;
    // width: 100%;
  }
  .tpls {
    display: flex;
    overflow-x: auto;
    gap: 8px;
    padding: 16px 16px;
    padding-bottom: 0;
    scrollbar-width: none; // Firefox
    min-height: 109px;
    &::-webkit-scrollbar {
      display: none; // Chrome, Safari, Edge
    }
    .item {
      cursor: pointer;
      border-radius: 8px;
      text-align: center;
      height: 100%;
      box-sizing: border-box;
      &.active {
        .name {
          color: #f76b1b;
        }
        .image-container {
          border-color: #f76b1b;
          &:hover {
            border-color: #f76b1b;
          }
        }
      }

      .image-container {
        width: 72px;
        height: 72px;
        overflow: hidden;
        border-radius: 8px;
        background-color: #f8f8f8;
        flex-shrink: 0;
        border: 2px solid transparent;
        margin-bottom: 4px;

        .item-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      .name {
        font-size: 12px;
        font-weight: 500;
        color: #aaa;
      }
    }
  }

  .bottom-buttons {
    display: flex;
    gap: 16px;
    padding: 16px 16px;
    .btn-primary {
      flex: 1;
      height: 40px;
      color: white;
      border: none;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      background: #f76b1b;
      padding: 0px 20px;
      &:disabled {
        opacity: 0.5;
        pointer-events: none;
      }
      &:active:not(:disabled) {
        opacity: 0.9;
      }
    }
    .btn-secondary {
      height: 40px;
      color: #f76b1b;
      border: none;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      background: #fbe6db;
      padding: 0px 20px;
      &:disabled {
        opacity: 0.5;
        pointer-events: none;
      }
      &:hover:not(:disabled) {
        opacity: 0.9;
      }
    }
  }
</style>
